import {Component, ElementRef, ViewChild} from "@angular/core";

import {PublishService} from "./publish.service";
import {AlertController, NavController, ToastController} from "ionic-angular";
import {ImagePicker} from "@ionic-native/image-picker";
import {TabsPage} from "../tabs/tabs";
import {Transfer, TransferObject} from "@ionic-native/transfer";
import {File} from "@ionic-native/file";
import {LoginPage} from "../login/login";
import {UserData} from "../../common/user.data";

@Component({
  selector: 'page-publish',
  templateUrl: 'publish.html',
  providers: [PublishService, ImagePicker, Transfer, File]
})

export class PublishPage {

  public articleForm: any = {title: null, movieURL: null, showPic: null, content: '', token: null};
  @ViewChild('iframe') iframe: ElementRef;
  fileTransfer: TransferObject = this.transfer.create();

  private imagePickerOpt = {
    maximumImagesCount: 1,
    width: 800,
    height: 800,
    quality: 80
  };


  constructor(public publishService: PublishService,
              public imagePicker: ImagePicker,
              public alertCtrl: AlertController,
              public toast: ToastController,
              public user: UserData,
              public navCtrl: NavController,
              private transfer: Transfer, private file: File) {

    if (!this.user.token) {
      this.alertCtrl.create({
        message: '您未登录,请先登录',
        buttons: [{
          text: '去登录',
          handler: () => {
            navCtrl.push(LoginPage);
          }
        }]
      }).present();
    }
  }

  insertImgClick(filePath: string) {
    this.file.readAsDataURL(filePath.substring(0, filePath.lastIndexOf("/")), filePath.substring(filePath.lastIndexOf("/") + 1)).then(res => {
      let doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;
      const link = "<img style='display: block' width='100%' imgName='" + filePath.substring(filePath.lastIndexOf("/") + 1) + "' src='" + res + "'><hr /><br>";
      doc.body.innerHTML = doc.body.innerHTML + link;
      setTimeout(function(){
        doc.body.focus();
      }, 1000);
    }, err => {
      this.toast.create({
        message: "图片上传失败功" + err,
        duration: 2000,
        position: 'top'
      }).present();
    }).catch(err => {
      this.toast.create({
        message: "图片上传失败功" + err,
        duration: 2000,
        position: 'top'
      }).present();
    });
  }

  // 打开手机相册
  private openImgPicker() {
    this.imagePicker.getPictures(this.imagePickerOpt).then((results) => {
      for (let i = 0; i < results.length; i++) {
        this.insertImgClick(results[i])
      }
    }, (err) => {
      this.toast.create({
        message: "图片上传失败功" + err,
        duration: 2000,
        position: 'top'
      }).present();
    });
  }

  publish() {
    let doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;
    if (!this.articleForm.title) {
      this.toast.create({
        message: "请输入标题!",
        duration: 2000,
        position: 'top'
      }).present();
      return;
    }
    if (!doc.body.innerHTML) {
      this.toast.create({
        message: "请输入文章内容!",
        duration: 2000,
        position: 'top'
      }).present();
      return;
    }
    this.articleForm.content = doc.body.innerHTML;
    this.articleForm.token = this.user.token;
    this.publishService.publish(this.articleForm).subscribe(res => {
      if (res.status === "SUCCESS") {
        this.alertCtrl.create({
          subTitle: '发布成功!',
          buttons: [{
            text: '确认',
            handler: () => {
              this.navCtrl.push(TabsPage)
            }
          }]
        }).present();
      } else {
        this.toast.create({
          message: res.message,
          duration: 2000,
          position: 'top'
        }).present();
      }
    }, error => {
      this.toast.create({
        message: "发布失败,请重试!",
        duration: 2000,
        position: 'top'
      }).present();
    });
  }

  cancel() {
    this.navCtrl.popToRoot(TabsPage);
  }

  insertPicClick() {
    this.openImgPicker();
  }

  insertMovieClick() {
    let doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;

    let alert = this.alertCtrl.create({
      title: '视频链接地址',
      message: '请选择分享视频中[通用代码]中链接地址直接粘贴到视频地址框',
      inputs: [{
        name: 'movieUrl',
        placeholder: '视频地址',
        value: this.articleForm.movieURL,
      }],
      buttons: [{
        text: '取消',
        role: 'cancel',
        handler: data => {
          console.log('Cancel clicked');
        }
      }, {
        text: '确认',
        handler: data => {
          this.articleForm.movieURL = data.movieUrl;
        }
      }]
    });
    alert.present();
    setTimeout(function(){
      doc.body.focus();
    }, 1000);
  }

  insertLink() {
    let doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;
    let alert = this.alertCtrl.create({
      title: '添加连接',
      inputs: [{
        name: 'linkName',
        placeholder: '连接名称'
      }, {
        name: 'linkURL',
        placeholder: '连接地址'
      }],
      buttons: [{
        text: '取消',
        role: 'cancel',
        handler: data => {
          console.log('Cancel clicked');
          doc.body.focus();
        }
      }, {
        text: '确认',
        handler: data => {
          if (!data.linkURL) {
            this.toast.create({
              message: "请输入连接地址!",
              duration: 2000,
              position: 'top'
            }).present();
            return;
          }
          if (!data.linkURL.startsWith("http")) {
            data.linkURL = "http://" + data.linkURL
          }
          const link = "<a href='" + data.linkURL + "'>" + (data.linkName ? data.linkName : data.linkURL) + "</a>";
          doc.body.innerHTML = doc.body.innerHTML + link;
          setTimeout(function(){
            doc.body.focus();
          }, 2000);
        }
      }]
    });
    alert.present();
  }
  ionViewDidLoad() {

  }
}
